package blog.gui;

import javax.microedition.lcdui.*;

import blog.*;
import blog.controller.*;

public class HtmlTagPromptGui extends Form implements IBaseGui, CommandListener, ItemStateListener {
	
	private Command cmdBack = new Command( ConstString.CMD_BACK, Command.BACK, 0 );
	private Command cmdOk = new Command( ConstString.CMD_INSERT_INPUT_ONLY, Command.OK, 0 );
	
	private TextField htmlTag;
	private ChoiceGroup select;
	
	int insertPos;
	int cutIndex;

	public HtmlTagPromptGui( int insertPos, int cutIndex, boolean auto ) {
		super(ConstString.GUI_TITLE_HTML_TAG_PROMPT);
		
		this.addCommand(cmdBack);
		/* Start Modify 08-10-20 */
		//addCommand(cmdOk);
		/* End Modify 08-10-20 */
		setCommandListener(this);
		
		if ( auto )
		{
			htmlTag = new TextField( ConstString.GUI_HTML_TAG_PROMPT_TAG, "<", 50, TextField.ANY );
			/* Start Modify 08-10-20 */
			addCommand(cmdOk);
			/* End Modify 08-10-20 */
		}
		else
		{
			htmlTag = new TextField( ConstString.GUI_HTML_TAG_PROMPT_TAG, "", 50, TextField.ANY );
		}
		
		select = new ChoiceGroup( ConstString.GUI_HTML_TAG_PROMPT_SELECT, ChoiceGroup.EXCLUSIVE, ConstString.GUI_HTML_TAG_PROMPT_DATA, null);
		select.insert(0, ConstString.GUI_HTML_TAG_PROMPT_SELECT_DEFAULT, null);
		select.setSelectedIndex(0, true);
		
		append(htmlTag);
		append(select);
		setCommandListener(this);
		
		this.setItemStateListener(this);
		
		this.insertPos = insertPos;
		this.cutIndex = cutIndex;
	}

	public int getIdentify() {
		return 0;
	}

	public void notifyChanged(Object param) {

	}

	public void commandAction(Command cmd, Displayable arg1) {
		if ( cmd==cmdBack )
		{
			SysRuntime.guiManager.back();
		}
		else if ( cmd==cmdOk )
		{
			AdvanceBodyEdit.getInstance().insertSomething(htmlTag.getString().substring(cutIndex), insertPos);
			SysRuntime.guiManager.back();
		}
	}

	public void itemStateChanged(Item item) {
		if ( item==this.htmlTag )
		{
			String input = htmlTag.getString().toLowerCase();
			select.deleteAll();
			select.append(ConstString.GUI_HTML_TAG_PROMPT_SELECT_DEFAULT, null);
			for( int i=0; i<ConstString.GUI_HTML_TAG_PROMPT_DATA.length; i++ )
			{
				if ( input==null || input.length()==0 || ConstString.GUI_HTML_TAG_PROMPT_DATA[i].startsWith(input) )
				{
					select.append(ConstString.GUI_HTML_TAG_PROMPT_DATA[i], null);
				}
			}
			select.setSelectedIndex(0, true);
			
			if ( input==null || input.length()==0 )
			{
				this.removeCommand(this.cmdOk);
			}
			else
			{
				this.addCommand(this.cmdOk);
			}
		}
		else if ( item==select )
		{
			AdvanceBodyEdit.getInstance().insertSomething( select.getString(select.getSelectedIndex()).substring(this.cutIndex), insertPos );
			SysRuntime.guiManager.back();
		}
	}

}